import { appRef } from "@/models/app.ref";
import { BaseServices } from "./base.services";
import { DrawModelEnum } from "@/models/aidraw";
import { imageUrlToBase64 } from "@/utils/common.methods";

export class DrawService extends BaseServices {
  private static _ins: DrawService = new DrawService();
  public static get ins(): DrawService {
    return this._ins ? this._ins : (this._ins = new DrawService());
  }

  /**
   * AI 绘画
   * 根据提示词生成图片
   * @param prompt
   * @param negative_prompt
   * @param model_name
   * @returns
   */
  public generate(prompt: string, negative_prompt: string = "", model_name: DrawModelEnum = DrawModelEnum.Normal): Promise<string> {
    const url = "https://www.13042332817.top/img_generate";
    const data = { prompt, negative_prompt, model_name };
    return new Promise<string>((reslove) => {
      this.request(url, data)
        .then(async (res: { task_id: string }) => {
          const task_id = res.task_id;
          const checkTaskStatus = async () => {
            const statusResponse = await fetch(`https://www.13042332817.top/img_generate_task/${task_id}`);
            console.log("statusResponse", statusResponse);

            if (statusResponse.status == 200) {
              const blob = await statusResponse.blob();
              const base64 = await imageUrlToBase64(URL.createObjectURL(blob));
              appRef.aidraw.updateImage(task_id, base64, prompt, negative_prompt, model_name);
              reslove(res.task_id);
            } else {
              const statusData = await statusResponse.json();
              if (statusData.status === "进行中") {
                setTimeout(checkTaskStatus, 1000);
              } else {
                console.error("错误: ", statusData.error);
                throw new Error("图片生成错误");
              }
            }
          };
          checkTaskStatus();
        })
        .catch((err) => {
          reslove(err);
        });
    });
  }
}

export const drawService: DrawService = DrawService.ins;
